<template>
    <div>

        <div style="margin-bottom:5px;">
            <el-input v-model="name" placeholder="请输入药品名称" style="width:200px;" @keyup.enter.native="loadPost"></el-input>
            <el-button type="primary" style="margin-left:5px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button>
            <el-button type="primary" @click="add">新增</el-button>

        </div>
        <el-table :data="tableData"
                  :header-cell-style="{background: '#f3f6fd',color:'#555'}">
            <el-table-column prop="id" label="药品编码" width="120">
            </el-table-column>
            <el-table-column prop="name" label="药品名称" width="200">
            </el-table-column>
            <el-table-column prop="type" label="药品类型" width="200">
            </el-table-column>
            <el-table-column prop="price" label="价格" width="200">
            </el-table-column>
            <el-table-column prop="spec" label="规格" width="200">
            </el-table-column>
            <el-table-column prop="code" label="条码" width="200">
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="200">
            </el-table-column>
            <el-table-column prop="operate" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="stock(scope.row)">库存</el-button>
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm title="确定删除" @confirm="del(scope.row.id)" style="margin-left:5px;">
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[2, 5, 10, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">

        </el-pagination>

        <el-dialog
                title="提示"
                :visible.sync="centerDialogVisible"
                width="30%"
                center>
            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="药品名称" prop="name">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="药品类型" prop="type">
                    <el-col :span="20">
                        <el-input v-model="form.type"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-col :span="20">
                        <el-input v-model="form.price"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="规格" prop="spec">
                    <el-col :span="20">
                        <el-input v-model="form.spec"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="条码" prop="code">
                    <el-col :span="20">
                        <el-input v-model="form.code"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-col :span="20">
                        <el-input v-model="form.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
                title="库存"
                :visible.sync="stockDialogVisible"
                width="60%"
                center>
            <el-button type="primary" @click="addItem">新增</el-button>
            <el-table :data="stocks"
                      :header-cell-style="{background: '#f3f6fd',color:'#555'}">
                <el-table-column v-if="false" prop="id" label="编码" width="120">
                </el-table-column>
                <el-table-column prop="name" label="药品名称" width="200">
                </el-table-column>
<!--                <el-table-column prop="exp" label="有效期" width="100">-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="produceDate" label="入库日期" width="200">-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="amount" label="数量" width="200">-->
<!--                </el-table-column>-->
                <el-table-column prop="exp" label="有效期">
                    <template slot-scope="scope">
                        <!-- 编辑模式 -->
                        <el-input v-if="scope.$index === editingRowIndex" v-model="scope.row.exp" size="small"></el-input>
                        <!-- 非编辑模式 -->
                        <span v-else @dblclick="startEdit(scope.$index)">{{ scope.row.exp }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="produceDate" label="入库日期">
                    <template slot-scope="scope">
                        <!-- 编辑模式 -->
                        <el-date-picker v-if="scope.$index === editingRowIndex" v-model="scope.row.produceDate" size="small"></el-date-picker>
                        <!-- 非编辑模式 -->
                        <span v-else @dblclick="startEdit(scope.$index)">{{ scope.row.produceDate }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="数量">
                    <template slot-scope="scope">
                        <!-- 编辑模式 -->
                        <el-input v-if="scope.$index === editingRowIndex" v-model="scope.row.amount" size="small"></el-input>
                        <!-- 非编辑模式 -->
                        <span v-else @dblclick="startEdit(scope.$index)">{{ scope.row.amount }}</span>
                    </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button v-if="scope.$index === editingRowIndex" type="text" size="small" @click="saveRow(scope.$index, scope.row)">保存</el-button>
                        <el-button v-else type="text" size="small" @click="deleteRow(scope.$index, scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

    </div>
</template>

<script>
    import ApiService from "@/apiService";

    export default {
        name: 'Medicine',
        data() {
            return {
                editingRowIndex: -1,
                tableData: [],
                pageSize:20,
                pageNum:1,
                total:0,
                medicineId:'',
                name:'',
                centerDialogVisible:false,
                form:{
                    id:'',
                    name:'',
                    type:'',
                    spec:'',
                    price:'',
                    code:'',
                    remark:'',
                },
                stockDialogVisible:false,
                stocks:[],
                //     {
                //     id:'',
                //     name:'',
                //     exp:'',
                //     indate:'',
                //     amount:'',
                // },
                rules:{
                    name:[
                        {required:true,message:'请输入药品名称',trigger:'blur'},
                    ],
                }

            }
        },

        methods:{

            // 转换为'yyyy-MM-dd'格式
            formatDate(date) {
                const year = date.getFullYear();
                const month = ("0" + (date.getMonth() + 1)).slice(-2);
                const day = ("0" + date.getDate()).slice(-2);
                return `${year}-${month}-${day}`;
            },

            addItem() {
                this.stocks.push({medicineId:this.medicineId, name: this.name }); // 添加新行，id可以是任何唯一标识符
                this.editingRowIndex = this.stocks.length - 1; // 设置新增行的索引为当前正在编辑的行
            },
            startEdit(index) {
                this.editingRowIndex = index;
            },

            async saveRow(index, data) {
                if (!data.id){
                    data.produceDate =  this.formatDate(data.produceDate);
                }
                console.log(data);
                const response = await ApiService.post('/medicine/stockSaveOrUpdate', data);
                // 发送API请求保存数据到服务器
                // 成功后关闭编辑模式
                this.editingRowIndex = -1;
            },

            async deleteRow(index,id) {
                // 发送API请求删除该行数据
                // 删除后从tableData数组中移除该条目
                const response = await ApiService.get('/medicine/stockDel?id=' + id);
                this.stocks.splice(index, 1);
            },
            add(){
                this.centerDialogVisible = true
                this.$nextTick(()=>{
                    this.resetForm()
                    this.form.id = ''})
            },

            mod(row){
                this.centerDialogVisible = true
                this.$nextTick(()=>{
                    this.form.id = row.id
                    this.form.name = row.name
                    this.form.type = row.type
                    this.form.spec = row.spec
                    this.form.price = row.price
                    this.form.code = row.code
                    this.form.remark = row.remark
                })
            },
            async stock(row){
                const response = await ApiService.get('/medicine/stockList?medicineId=' + row.id);
                if(response.code===200){
                    this.stockDialogVisible = true
                    this.stocks=response.data
                    this.$nextTick(()=>{
                        this.stocks.forEach(item => {
                            item.name = row.name; // 将所有item的value字段设置为commonValue
                        });
                    })
                    this.medicineId = row.id;
                    this.name = row.name;
                }else{
                    this.$message({message:"失败",type:'error'})
                }

            },

            save(){
                this.$refs.form.validate((valid)=>{
                    if(valid){
                        this.saveOrUpdate();
                    }else{
                        console.log('error submit!!')
                        return false;
                    }
                });


            },

            async saveOrUpdate(){
                const response = await ApiService.post('/medicine/saveOrUpdate', this.form);
                if(response.code===200){
                    this.$message({message:"成功",type:'success'})
                    this.centerDialogVisible = false
                    this.loadPost()
                }else{
                    this.$message({message:"失败",type:'error'})
                }
            },
            //删除功能
            async del(id){
                const response = await ApiService.get('/medicine/del?id='+id);
                if(response.code===200){
                    this.$message({message:"成功",type:'success'})
                    this.centerDialogVisible = false
                    this.loadPost()
                }else{
                    this.$message({message:"失败",type:'error'})
                }
            },


            resetForm(){
                this.$refs.form.resetFields();
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum=1
                this.pageSize=val
                this.loadPost()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum=val
                this.loadPost()
            },

            resetParam(){
                this.name='';
            },

            async loadPost(){
                const response = await ApiService.post('/medicine/listPage', {
                    pageSize:this.pageSize,
                    pageNum:this.pageNum,
                    param:{
                        name:this.name,
                    }
                });

                if(response.code===200){
                    this.tableData=response.data
                    this.total=response.total
                }else{
                    alert('获取数据失败')
                }
            }
        },


        beforeMount(){
            // this.loadGet()
            this.loadPost()
        }



    }
</script>


<style scoped>

</style>
